package com.xingkeduo.business.transformation.json;

import java.util.Iterator;
import java.util.List;

import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xingkeduo.pojo.table.CraftsmanTraceTO;
import com.xingkeduo.pojo.table.CraftsmanTraceTO.Type;
import com.xingkeduo.util.pojo.base.BaseJson;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.InputParamException;
import com.xingkeduo.util.tool.CommonUtil;

/**
 * 求职者考核结果封装类
 * 
 * @author 高杰
 * @time 2018年12月25日 下午1:45:17
 * @description
 */
@Component
public class CraftsmanTraceJTO extends BaseJson {
	public static CraftsmanTraceTO createTableForNew(String json) throws Throwable {
		CraftsmanTraceTO table = new CraftsmanTraceTO();
		JsonNode root = validJson(json);
		if (root == null)
			throw new InputParamException(InputParamException.Type.INVALID, "参数");

		table.setType(validType(root, YesNoEnum.YES)).setLogin(validLogin(root, YesNoEnum.YES));

		return table;
	}

	public static ObjectNode toJson(CraftsmanTraceTO table) {
		ObjectNode root = MAPPER.createObjectNode();

		if (table != null) {
			if (table.getType() != null) {
				root.put("type_value", table.getType().getValue());
				root.put("type_desc", table.getType().getDesc());
			}
			if (table.getLogin() != null)
				root.put("login", table.getLogin());

			toBaseJson(root, table);
		}

		return root;
	}

	public static ArrayNode toJson(List<CraftsmanTraceTO> tables) {
		ArrayNode root = MAPPER.createArrayNode();

		if (!CommonUtil.isEmpty(tables))
			for (Iterator<CraftsmanTraceTO> iterator = tables.iterator(); iterator.hasNext();) {
				root.add(toJson(iterator.next()));
			}

		return root;
	}

	public static Type validType(JsonNode node, YesNoEnum isRequired) throws Throwable {
		String key = "type";
		if (YesNoEnum.YES == isRequired && !node.has(key))
			throw new InputParamException(InputParamException.Type.NULL, key);

		if (node.has(key)) {
			String value = node.path(key).asText().trim();
			if (!Type.validValue(value))
				throw new InputParamException(InputParamException.Type.INVALID, key + " error");
			return Type.getType(value);
		}
		return null;
	}

	public static String validLogin(JsonNode node, YesNoEnum isRequired) throws Throwable {
		String key = "login";
		if (YesNoEnum.YES == isRequired && !node.has(key))
			throw new InputParamException(InputParamException.Type.NULL, key);

		if (node.has(key)) {
			String value = node.path(key).asText().trim();
			if (CommonUtil.isEmpty(value) || value.length() > 50)
				throw new InputParamException(InputParamException.Type.INVALID, key + " error");
			return value;
		}
		return null;
	}
}
